package com.lixinlei.mc.api.sms.cat;

import com.alibaba.fastjson.JSON;
import org.smslib.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.smslib.Message.MessageEncodings;
import org.smslib.modem.SerialModemGateway;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/windows/sms/cat")
public class WindowsSmsCatSendController {

    @Autowired
    private SmsCatSendService smsCatSendService;

    @GetMapping("/start")
    public String start() {
        WindowsSmsCatSendController.OutboundNotification outboundNotification
                = new WindowsSmsCatSendController.OutboundNotification();

        SerialModemGateway gateway = new SerialModemGateway(
                "modem.com3",
                "COM3",
                9600,
                "null",
                "null");
        gateway.setInbound(false);
        gateway.setOutbound(true);
        gateway.setSimPin("0000");

        try {
            Service.getInstance().setOutboundMessageNotification(outboundNotification);
            Service.getInstance().addGateway(gateway);  //将网关添加到短信猫服务中
            Service.getInstance().startService();   //启动服务，进入短信发送就绪状态
        } catch (Exception e) {
            return e.getMessage();
        }
        return "SMS CAT Service Started...";
    }

    @GetMapping("/send/{phone}/{content}")
    public String send(@PathVariable("phone") String phone, @PathVariable("content") String content) throws InterruptedException, SMSLibException, IOException {
        String msg = smsCatSendService.send(phone, content);
        return msg;
    }

    @RequestMapping("/stop")
    public String stopService() {
        try {
            Service.getInstance().stopService();
        } catch (Exception e) {
            return e.getMessage();
        }
        return "SMS CAT Service Stopped.";
    }

    public class OutboundNotification implements IOutboundMessageNotification{
        @Override
        public void process(AGateway aGateway, OutboundMessage outboundMessage) {
            System.out.println("OutboundNotification aGateway.getGatewayId(): " + aGateway.getGatewayId());
            System.out.println("OutboundNotification outboundMessage:" + outboundMessage);
        }
    }

}
